package com.pdf.pdfserver.service.read.text;

import com.pdf.pdfserver.enums.FileSuffixEnum;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @Author songfz
 * @Description
 * @Date 2022/1/4
 */
@Service("execlReadService")
public class ExeclReadService implements IfReadService {

    private static int maxx = 65536;

    private static Logger LOG = LoggerFactory.getLogger(IfReadService.class);
    @Override
    public String read(FileSuffixEnum suffixEnum, InputStream fis){

        StringBuilder sb = new StringBuilder();
        //Workbook 不能close 关闭fis即可
        Workbook wb = null;
       try{
           if(FileSuffixEnum.XLS.compareTo(suffixEnum) == 0) {
               wb = new HSSFWorkbook(fis);
           }
           else {
               wb = new XSSFWorkbook(fis);
           }

        for(int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets() && sb.length() < maxx; sheetIndex++) {
            //读取sheet 0
            Sheet sheet = wb.getSheetAt(sheetIndex);
//设置变量的第一行
            int firstRowIndex = sheet.getFirstRowNum();
            //设置变量的行
            int lastRowIndex = sheet.getLastRowNum();
            LOG.info("firstRowIndex: "+firstRowIndex);
            LOG.info("lastRowIndex: "+lastRowIndex);

            //遍历行
            for(int rIndex = firstRowIndex; rIndex <= lastRowIndex && sb.length() < maxx; rIndex++) {
                LOG.info("rIndex: " + rIndex);
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    int firstCellIndex = row.getFirstCellNum();
                    int lastCellIndex = row.getLastCellNum();
                    LOG.info("1c: " + firstCellIndex + "lc: " + lastCellIndex);
                    //遍历列
                    for (int cIndex = firstCellIndex; cIndex < lastCellIndex && sb.length() < maxx; cIndex++) {
                        Cell cell = row.getCell(cIndex);
                        if (cell != null) {
                            sb.append(cell.toString());
                            sb.append(" ");
                        }
                    }
                }
            }
        }
       }catch (IOException e){
           LOG.error(e.getMessage(),e);
       }finally {

           Optional.ofNullable(fis).ifPresent(in1-> {
               try {
                   in1.close();
               } catch (IOException e) {
                   LOG.error(e.getMessage(),e);
               }
           });
       }
       return sb.toString();
    }
}
